#include "StdAfx.h"
#include "deadZ80.h"
#include "opcodes.h"

int CDeadZ80::ExecuteOpcodeED()
{
	unsigned char opcode = ReadMemory8(pc++);
	unsigned short stmp;
	unsigned char tmp,tmp2;
	unsigned long ltmp;

	switch(opcode) {
		case 0x42:	SBC16(HL,BC);	cycles += 14;	break;	//sbc hl,bc
		case 0x52:	SBC16(HL,DE);	cycles += 14;	break;	//sbc hl,de
		case 0x62:	SBC16(HL,HL);	cycles += 14;	break;	//sbc hl,hl
		case 0x72:	SBC16(HL,sp);	cycles += 14;	break;	//sbc hl,sp
		case 0x7A:	ADC16(HL,sp);	cycles += 14;	break;	//adc hl,sp
		case 0x43:	//ld (nn),bc
			WriteMemory16(ReadMemory16(pc),BC);
			pc += 2;
			cycles += 14;
			break;
		case 0x44:	//neg
			tmp = A;
			if(tmp != 0x80)
				A = A - 0x80;
			F = 0x28;
			if(tmp == 0x80)
				F |= FLAG_P;
			if(tmp != 0x00)
				F |= FLAG_C;
			if(A == 0)
				F |= FLAG_Z;
			if(A & 0x80)
				F |= FLAG_N;
			//todo: set h flag
			break;
		case 0x4A:	ADC16(HL,BC);	cycles += 14;	break;	//sbc hl,bc
		case 0x4B:	//ld bc,(nn)
			BC = ReadMemory16(ReadMemory16(pc));
			pc += 2;
			cycles += 14;
			break;
		case 0x53:	//ld (nn),de
			WriteMemory16(ReadMemory16(pc),DE);
			pc += 2;
			cycles += 14;
			break;
		case 0x56:	//im 1
			intmode = 1;
			cycles += 8;
			break;
		case 0x5A:	ADD16(HL,DE);		cycles += 10;	break;

		case 0x5B:	//ld de,(nn)
			DE = ReadMemory16(ReadMemory16(pc));
			pc += 2;
			cycles += 14;
			break;
		case 0x67:
			tmp = ReadMemory8(HL);
			WriteMemory8(HL,(tmp >> 4)| (A << 4));
			A = (A & 0xF0) | (tmp & 0xF);
			F = F & 1;
			if(A == 0)
				F |= FLAG_Z;
			if(A & 0x80)
				F |= FLAG_N;
			if(parity[A])
				F |= FLAG_P;
			break;
		case 0x6A:	ADD16(HL,HL);		cycles += 15;	break;

		case 0x6B:	//ld hl,(nn)
			HL = ReadMemory16(ReadMemory16(pc));
			pc += 2;
			cycles += 14;
			break;
		case 0x6F:
			tmp = ReadMemory8(HL);
			WriteMemory8(HL,(tmp << 4)| (A & 0xF));
			A = (A & 0xF0) | (tmp >> 4);
			F = F & 1;
			if(A == 0)
				F |= FLAG_Z;
			if(A & 0x80)
				F |= FLAG_N;
			if(parity[A])
				F |= FLAG_P;
			break;
		case 0x7B:	//ld sp,(nn)
			sp = ReadMemory16(ReadMemory16(pc));
			pc += 2;
			cycles += 14;
			break;

		case 0x73:	//LD (nn),SP
			WriteMemory16(ReadMemory16(pc),sp);
			pc += 2;
			cycles += 14;
			break;

		case 0xA0:	//ldi
			LDI();
			break;
		case 0xA1:	//cpi
			CPI();
			break;
		case 0xA3:	//outi
			B--;
			iowritefunc(user,BC,ReadMemory8(HL++));
			break;
		case 0xA8:	//ldd
			LDD();
			break;
		case 0xA9:	//cpd
			CPD();
			break;

		case 0xB0:	//ldir
			LDIR();
			break;
		case 0xB1:	//cpir
			CPIR();
			break;
		case 0xB3:	//otir
			B--;
			iowritefunc(user,BC,ReadMemory8(HL++));
			pc -= 2;
			break;

		case 0xB8:	//lddr
			LDDR();
			break;

		case 0xB9:	//cpdr
			CPDR();
			break;

		default:
			message("bad ED opcode $%02X\n",opcode);
			return(1);
	}
	return(0);
}
